#include "obs-context-wrapper.h"
#include <obs.h>

OBSContextWrapper::OBSContextWrapper(const char* locale, 
                                     const char* module_config_path,
                                     profiler_name_store_t* store,
                                     bool auto_init)
    : locale_(locale ? locale : "en-US")
    , module_config_path_(module_config_path ? module_config_path : "")
    , store_(store)
    , initialized_(false)
    , auto_init_(auto_init)
{
    if (auto_init_) {
        Initialize();
    }
}

OBSContextWrapper::~OBSContextWrapper()
{
    if (initialized_) {
        Shutdown();
    }
}

OBSContextWrapper::OBSContextWrapper(OBSContextWrapper&& other) noexcept
    : locale_(std::move(other.locale_))
    , module_config_path_(std::move(other.module_config_path_))
    , store_(other.store_)
    , initialized_(other.initialized_)
    , auto_init_(other.auto_init_)
{
    // 移动后，原对象应该处于未初始化状态
    other.initialized_ = false;
    other.store_ = nullptr;
    other.auto_init_ = false;
}

OBSContextWrapper& OBSContextWrapper::operator=(OBSContextWrapper&& other) noexcept
{
    if (this != &other) {
        if (initialized_) {
            Shutdown();
        }
        
        locale_ = std::move(other.locale_);
        module_config_path_ = std::move(other.module_config_path_);
        store_ = other.store_;
        initialized_ = other.initialized_;
        auto_init_ = other.auto_init_;
        
        other.initialized_ = false;
        other.store_ = nullptr;
        other.auto_init_ = false;
    }
    return *this;
}

bool OBSContextWrapper::Initialize()
{
    if (initialized_) {
        return true; // 已经初始化过了
    }
    
    const char* config_path = module_config_path_.empty() ? nullptr : module_config_path_.c_str();
    
    // 调用 obs_startup
    bool startup_success = obs_startup(locale_.c_str(), config_path, store_);
    
    if (startup_success) {
        // 验证初始化是否真的成功
        initialized_ = obs_initialized();
    } else {
        initialized_ = false;
    }
    
    return initialized_;
}

void OBSContextWrapper::Shutdown()
{
    if (initialized_) {
        obs_shutdown();
        initialized_ = false;
    }
}

bool OBSContextWrapper::IsInitialized() const
{
    // 首先检查内部状态，然后验证 OBS 全局状态
    return initialized_ && obs_initialized();
} 